import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * @author ZhiWen Ren
 * @version 1.0
 * @description: LeetCode-347- 前 K 个高频元素
 * @date 2025/7/14 15:04
 */
public class Solution347 {
    public static int[] topKFrequent(int[] nums, int k) {
        int[] ans = new int[k];
        Map<Integer, Integer> hashMap = new HashMap<>();
        for (int num : nums) {
            hashMap.put(num, hashMap.getOrDefault(num, 0) + 1);
        }
        PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(k, Comparator.comparingInt(Map.Entry::getValue));

        // pq.addAll(hashMap.entrySet());

        for (Map.Entry<Integer, Integer> integerIntegerEntry : hashMap.entrySet()) {
            pq.offer(integerIntegerEntry);
            if (pq.size() > k) {
                // 动态维护一个k个大小的小根堆
                pq.poll();
            }
        }
        for (int i = k - 1; i >= 0; i--) {
            ans[i] = pq.poll().getKey();
        }
        return ans;
    }

    public static void main(String[] args) {
        topKFrequent(new int[]{1,1,1,2,2,3},2);
    }
}
